
var http = require('http');
var https = require('https');
var url = require('url');

var httpclient = {};

httpclient.get = function(u, callback){
	var request = null;
	
	var urlparts = url.parse(u, true);
	if (urlparts.protocol === "http:")
	{
		request = http.get(u);
	}
	else if (urlparts.protocol === "https:")
	{
		request = https.get(u);	
	}
	else
	{
		console.error("bad protocol in url: "+ u);
		throw new Error("bad protocol in url: "+ u);
	}

	var chunks = [];
	var total_size = 0;
	request.on("response", function(res){
		res.on("data", function(chunk){
			chunks.push(chunk);
			total_size += chunk.length;
		});
		res.on("end", function(){
			var result = Buffer.concat(chunks, total_size);
			callback(result);
		});
	});
	request.on("error", function(e){
		console.error("get request failed for url: "+u+", error: "+e.message);
		throw new Error("get request failed for url: "+u+", error: "+e.message);
	});
};

httpclient.post = function(u, data, callback){
	var urlparts = url.parse(u, true);
	var request = null;
	if (urlparts.protocol === 'http:')
	{
		request = http.request({
			hostname: urlparts.host,
			port: urlparts.port || 80,
			method: 'POST',
			path: urlparts.pathname
		});		
	}
	else if (urlparts.protocol === 'https:')
	{
		request = https.request({
			hostname: urlparts.host,
			port: urlparts.port || 443,
			method: 'POST',
			path: urlparts.pathname
		});
	}
	else
	{
		console.error("bad protocol in url: "+ u);
		throw new Error("bad protocol in url: "+ u);
	}

	var chunks = [];
	var total_size = 0;
	request.on('response', function(res){
		res.on("data", function(chunk){
			chunks.push(chunk);
			total_size += chunk.length;
		});
		res.on("end", function(){
			var result = Buffer.concat(chunks, total_size);
			callback(result);
		});
	});
	request.on("error", function(e){
		console.error("post request failed for url: "+u+", error: "+e.message);
		throw new Error("post request failed for url: "+u+", error: "+e.message);
	});

	request.setHeader('Content-Type', 'application/x-www-form-urlencoded');
	request.setHeader('Content-Length', data.length);
	request.end(data);
};

module.exports = httpclient;
